//
//  UploadVideoViewController.m
//  XJMTechnician
//
//  Created by 高波 on 2019/1/7.
//  Copyright © 2019 Mr.hu. All rights reserved.
//

#import "UploadVideoViewController.h"
#import "PhotoModel.h"
#import "AC_AVPlayerViewController.h"
@interface UploadVideoViewController () <UINavigationControllerDelegate, UIImagePickerControllerDelegate, UITableViewDelegate, UITableViewDataSource>
{
    NSMutableArray *_listArray;
    NSString *_videoUrlStr;
    UIImage *_cover;
    PhotoModel *_model;
}

@property (copy, nonatomic)NSURL *videoUrl;
@property (weak, nonatomic) IBOutlet UIButton *confirmButton;

@property (weak, nonatomic) IBOutlet UIButton *playButton;
@property (weak, nonatomic) IBOutlet UIImageView *coverImageView;


@end

@implementation UploadVideoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"我的视频";
    [self addRightBtn:[UIImage imageNamed:@"xiangceshangchuan"] Action:@selector(selectVideo)];
    [self adjustUI];
    [self getList];
}

- (void)getList
{
    [XJHttpClass TeachReceiveMineAlbumInformationToken:[XJToolClass getToken] andFinishblock:^(id response, NSString *errStr) {
        if (errStr) {
            [XJToolClass tipAnimationWith:errStr];
        }else{
            [PhotoModel mj_setupObjectClassInArray:^NSDictionary *{
                return @{
                         @"data": @"PhotoData",
                         @"videos" : @"Videos"
                         };
            }];
            _model = [PhotoModel mj_objectWithKeyValues:response];
            if (_model.data.videos.video_url.length) {
                
                AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:[NSURL URLWithString:_model.data.videos.video_url] options:nil];
                NSParameterAssert(asset);
                AVAssetImageGenerator *assetImageGenerator =[[AVAssetImageGenerator alloc] initWithAsset:asset];
                assetImageGenerator.appliesPreferredTrackTransform = YES;
                assetImageGenerator.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;
                
                CGImageRef thumbnailImageRef = NULL;
                CFTimeInterval thumbnailImageTime = 1;
                NSError *thumbnailImageGenerationError = nil;
                thumbnailImageRef = [assetImageGenerator copyCGImageAtTime:CMTimeMake(thumbnailImageTime, 60)actualTime:NULL error:&thumbnailImageGenerationError];
                
                if(thumbnailImageRef) {
                    _cover = [UIImage imageWithCGImage:thumbnailImageRef];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        self.coverImageView.image = _cover;
                    });
                    
                    [self.playButton setImage:[UIImage imageNamed:@"AJMP_icon_video_pause"] forState:UIControlStateNormal];
                    [self.playButton addTarget:self action:@selector(playVideo) forControlEvents:UIControlEventTouchUpInside];
                }else {
                    [self.playButton setImage:[UIImage imageNamed:@"tianjiaxiangce"] forState:UIControlStateNormal];
                    [self.playButton addTarget:self action:@selector(selectVideo) forControlEvents:UIControlEventTouchUpInside];
                }
            }
            
        }
    }];
}

- (void)playVideo
{
    NSURL *url = [NSURL URLWithString:_model.data.videos.video_url];
    AC_VideoModel *model1 = [[AC_VideoModel alloc] initWithName:@"视频" url:url];
    AC_AVPlayerViewController *vc = [[AC_AVPlayerViewController alloc] initWithVideoList:@[model1]];
    [self presentViewController:vc animated:YES completion:nil];
}

- (void)adjustUI
{
    self.coverImageView.contentMode = UIViewContentModeScaleAspectFill;
    self.coverImageView.clipsToBounds = YES;
    
    self.confirmButton.layer.cornerRadius = 20.0f;
    self.confirmButton.clipsToBounds = YES;
}

- (IBAction)uploadClick:(id)sender
{
    
}


- (void)selectVideo
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = NO;
    picker.videoMaximumDuration = 1.0; //视频最长长度
    picker.videoQuality = UIImagePickerControllerQualityTypeMedium; //视频质量
    
    //媒体类型：@"public.movie" 为视频  @"public.image" 为图片
    //这里只选择展示视频
    picker.mediaTypes = [NSArray arrayWithObjects:@"public.movie", nil];
    picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    [self presentViewController:picker animated:YES completion:^{
        
    }];
}


#pragma mark UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    NSString *mediaType=[info objectForKey:UIImagePickerControllerMediaType];
    
    if ([mediaType isEqualToString:@"public.movie"]){
        //如果是视频
        PHAsset *asset = info[UIImagePickerControllerPHAsset];//获得视频的URL
        PHImageManager *manager = [PHImageManager defaultManager];
        PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
        options.version = PHImageRequestOptionsVersionCurrent;
        options.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic;
        [manager requestAVAssetForVideo:asset options:options resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
            AVURLAsset *urlAsset = (AVURLAsset *)asset;
            _videoUrl = urlAsset.URL;
        }];
    }
    
    [self getToken];
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark -- 获取token
- (void)getToken
{
    [XJHttpClass ReceiveQiniuTokenFinishblock:^(id response, NSString *errStr) {
        if (errStr) {
            [XJToolClass tipAnimationWith:errStr];
        }else{
            NSDictionary * datadict = response[@"data"];
            NSString * qiniu_token = datadict[@"upToken"];
            [self uploadImageWithToken:qiniu_token];
        }
    }];
}

- (void)uploadImageWithToken:(NSString *)token
{
    [SVProgressHUD showWithStatus:@"上传视频中"];
    NSData *data = [NSData dataWithContentsOfURL:_videoUrl];
    NSString *filename = [NSString fileKey];
    filename = [filename stringByAppendingString:@".mp4"];
    QNUploadManager *upManager = [[QNUploadManager alloc] init];
    [upManager putData:data key:filename token:token
              complete: ^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
                  NSLog(@"key:%@",resp[@"key"]);
                  
                  dispatch_async(dispatch_get_main_queue(), ^{
                      [SVProgressHUD dismiss];
                  });
                  
                  if (info.isOK) {
                      _videoUrlStr = [NSString stringWithFormat:@"%@/%@",kQiniuBaseUrl,resp[@"key"]];
                      [self updateImageUrlStr:_videoUrlStr];
                  }
            } option:[QNUploadOption defaultOptions]
     ];
}

#pragma mark -- 更新图片
- (void)updateImageUrlStr:(NSString *)urlStr
{
    [XJHttpClass teachUploadPhotoVideotoken:[XJToolClass getToken] type:@"2" pics:nil videos:urlStr andFinishblock:^(id response, NSString *errStr) {
        if (errStr) {
            [XJToolClass tipAnimationWith:errStr];
        }else{
            [XJToolClass tipAnimationWith:@"上传成功!"];
            [self getList];
        }
    }];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _listArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }
    
    return cell;
}



@end
